package com.tongqu.protocol;

import com.alibaba.fastjson.JSON;
import com.tongqu.message.LoginMessage;
import com.tongqu.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
//@ChannelHandler.Sharable   is not allowed to be shared
public class TestCodec extends ByteToMessageCodec<Message> {

    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        log.info("开始编码----------------------------------发送消息");
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println(msg);
        String json= JSON.toJSONString(msg);
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);



//        // 1. 4 字节的魔数
//        out.writeBytes(new byte[]{1, 2, 3, 4});
//        // 2. 1 字节的版本,
//        out.writeByte(1);
//        // 3. 1 字节的序列化方式 jdk 0 , json 1
//        out.writeByte(0);
//        // 4. 1 字节的指令类型
//        out.writeByte(0);
//        // 5. 4 个字节
//        out.writeInt(0);
//        // 无意义，对齐填充
//        out.writeByte(0xff);
//        // 6. 获取内容的字节数组
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        ObjectOutputStream oos = new ObjectOutputStream(bos);
//        oos.writeObject(msg);
//        byte[] bytes = bos.toByteArray();
//        // 7. 长度
//        out.writeInt(bytes.length);
        // 8. 写入内容
        out.writeBytes(bytes);
        log.info("编码结束----------------------------------出站");
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("开始解码********************************接收信息");
//        int magicNum = in.readInt();
//        byte version = in.readByte();
//        byte serializerType = in.readByte();
//        byte messageType = in.readByte();
//        int sequenceId = in.readInt();
//        in.readByte();
//        int length = in.readInt();
        int length = in.readableBytes();
        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length);
//        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
//        TestUser message = (TestUser) ois.readObject();
//        log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
        String json = new String(bytes,StandardCharsets.UTF_8);
        log.info(json);
        LoginMessage message=JSON.parseObject(json, LoginMessage.class);
        System.out.println(message);
        log.debug("{}", message);
        out.add(message);
        log.info("解码完成********************************接收信息");

    }



}